package system

import (
	"github.com/gin-gonic/gin"
	"server/global"
	comRequest "server/model/common/request"
	"server/model/common/response"
	sysModel "server/model/system"
	sysRequest "server/model/system/request"
	sysService "server/service/system"
)

type RoleApi struct {
}

//首页列表
func (r *RoleApi) Index(c *gin.Context) {
	p := &sysRequest.SysRoleGetList{}
	if err := c.ShouldBind(p); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	//角色列表
	roleList, total, err := sysService.RoleServiceApp.GetList(p)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	//角色树结构里欸哦奥
	var roleTreeList []*sysModel.SysRole
	if p.Name == "" && p.DisplayName == "" {
		roleTreeList = sysService.RoleServiceApp.BuildTree(roleList)
	} else {
		roleTreeList = roleList
	}
	//权限列表
	permList, err := sysService.PermissionServiceApp.GetAll()
	permTreeList := sysService.PermissionServiceApp.BuildTree(permList)
	//显示输出
	response.OkWithData(gin.H{
		"roleList": roleTreeList,
		"total":    total,
		"permList": permTreeList,
	}, c)
}

//保存角色数据
func (r *RoleApi) Save(c *gin.Context) {
	p := &sysModel.SysRole{}
	if err := c.ShouldBind(p); err != nil {
		err = global.GvaValid.TranslateErr(err)
		response.FailWithMessage(err.Error(), c)
		return
	}
	if err := sysService.RoleServiceApp.SaveRole(p); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.Ok(c)
}

//删除角色
func (r *RoleApi) Destroy(c *gin.Context) {
	p := &comRequest.IdsReq{}
	if err := c.ShouldBind(p); err != nil {
		err = global.GvaValid.TranslateErr(err)
		response.FailWithMessage(err.Error(), c)
		return
	}
	err := sysService.RoleServiceApp.DelRole(p)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.Ok(c)
}
